package com.isyscore.iios.appdemo.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.isyscore.device.common.model.RespDTO;
import com.isyscore.iios.appdemo.dto.DeviceDTO;
import com.isyscore.iios.appdemo.service.DeviceService;
import com.isyscore.os.permission.exception.ErrorCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 该案例演示了如何在业务代码中调用设备集成的接口以及消息订阅，实现一些基本操作
 */
@Log4j2
@RestController
@Api(tags = "设备")
@RequestMapping("${app.apiPrefix:}/device")
public class DeviceController {
    @Autowired
    private DeviceService deviceService;

    /**
     * @param current 当前页数
     * @param size    每页的数据条数
     * @return 设备的分页列表
     */
    @ApiOperation("分页查询设备列表")
    @GetMapping("page")
    public RespDTO<IPage<DeviceDTO>> page(@RequestParam(value = "current") Integer current, @RequestParam(value = "size") Integer size) {
        //这里只使用分页的参数,更多的参数阅读openAPi说明文档。
        Map<String, Object[]> queryParams = new HashMap<>();
        queryParams.put("current", new Object[]{current});
        queryParams.put("size", new Object[]{size});
        try {
            return RespDTO.onSuc(deviceService.page(queryParams));
        } catch (Exception e) {
            return RespDTO.onFail(ErrorCode.FAIL.getCode(), e.getMessage());
        }
    }

    /**
     * 订阅该设备的属性上报消息并输出到控制台
     *
     * @param groupId  设备组ID
     * @param appId    过滤规则ID (到设备集成中的 规则引擎->数据过滤 中获取规则ID)
     * @param pk       设备类ID
     * @param devId    设备ID
     * @param username 有权限的用户的账号
     * @param password 有权限的用户的密码
     * @return
     */
    @ApiOperation("订阅设备属性数据")
    @GetMapping("subDeviceData")
    public RespDTO<?> subDeviceData(@RequestParam(value = "groupId") String groupId, @RequestParam("appId") String appId, @RequestParam("pk") String pk, @RequestParam("devId") String devId, @RequestParam("username") String username, @RequestParam("password") String password) {
        try {
            deviceService.subDeviceData(groupId, appId, pk, devId, username, password);
        } catch (Exception e) {
            return RespDTO.onFail(ErrorCode.FAIL.getCode(), e.getMessage());
        }
        return RespDTO.onSuc();
    }

}
